const config = require('../../../config')
const shopPlugin = require('../../../api')
Page({
  onLoad(options) {
    if (options && options.extraData) {
      var info = JSON.parse(decodeURIComponent(options.extraData))
      this.setData({
        info
      })
    }
  },

  gotoPay() {
    const cashierAppID = config.CASHIER_APP_ID
    wx.showLoading({
      title: "加载中……"
    });
    const navObj = {
      appId: cashierAppID,
      path: "/subPackCashier/pages/cashier/cashier",
      extraData: this.data.info,
      envVersion: 'release',
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: err,
          icon: 'none',
        });
        this.setData({
          needCheckOrderStatus: false
        })
      },
    }
    const version = wx.getSystemInfoSync().SDKVersion
    //2.23.4 以下有些收银小程序自动降级navigateToMiniProgram 接受不到extraData
    var useOpenEmbeddedMiniProgram = this.compareVersion(version, '2.23.4') >= 0

    if (useOpenEmbeddedMiniProgram && wx.openEmbeddedMiniProgram) {
      wx.openEmbeddedMiniProgram(navObj)
    } else {
      wx.navigateToMiniProgram(navObj)
    }
    this.data.needCheckOrderStatus = true
    this.setData({
      needCheckOrderStatus: true
    })
    shopPlugin.payUtil.setThirdPayData(this.data.info)
  },
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
  
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
  
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])
  
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
    return 0
  },

  onShow() {
    wx.hideLoading();
    if (this.data.needCheckOrderStatus) {
      this.checkOrderStatus()
    }
  },

  onHide: function () {
    this.clearTimeout()
  }, 

  onUnload() {
    this.clearTimeout()
  },

  checkOrderStatus() {
    var _this = this
    _this.clearTimeout()
    var delay = 10
    this.setData({
      delayTime: delay
    })
    _this.timer = setInterval(function() {
      if (delay >= 0) {
        _this.setData({
          delayTime: delay
        })
        delay -= 1;
        if (delay % 2 == 0) {
          shopPlugin.payUtil.checkOrderStatus(_this.data.info, (pay) => {
            if (pay || delay == 0) {
              shopPlugin.payUtil.payResult(pay, _this.data.info)
            } 
          })
        }
      } else {
        _this.clearTimeout()
      }
    }, 1000);
  },
  clearTimeout() {
    if (this.timer) clearInterval(this.timer);
  },
})
